package com.example.layered_arch.example.controller;

import com.example.layered_arch.example.entity.Product;
import com.example.layered_arch.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Controller
@RestController  // 标记为 REST 控制器，返回 JSON
@RequestMapping("/api")
public class ProductController {

    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;

    @GetMapping("/products")
    public List<Product> getProducts() {
        logger.info("收到前端请求：获取商品列表");
        List<Product> products = productService.getAllProducts();

        if (products == null || products.isEmpty()) {
            logger.warn("商品列表为空，可能是数据库没有数据！");
        } else {
            logger.info("查询到 {} 个商品", products.size());
            products.forEach(product -> logger.info("商品: {} - {}", product.getId(), product.getName()));
        }

        return products;  // 返回商品的 JSON 数据
    }
}

